package com.xiao.mall.foundation.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import javax.persistence.AttributeConverter;
import java.util.List;

public class ListObjectConverter<T> implements AttributeConverter<List<T>, String> {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(List<T> ts) {
        try {

            return objectMapper.writeValueAsString(ts);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<T> convertToEntityAttribute(String str) {
        if (!StringUtils.hasLength(str)) {
            return null;
        }

        try {
            List<T> map = objectMapper.readValue(str,
                    new TypeReference<List<T>>() {});
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}
